package com.skyworth.web.admin.table.controller;


import com.google.gson.JsonObject;
import com.skyworth.web.admin.table.form.TableForm;
import com.skyworth.web.admin.table.model.TableModel;
import com.skyworth.web.admin.table.service.ITableService;
import com.skyworth.web.admin.user.domain.UserModel;
import com.skyworth.web.admin.user.service.UserService;
import com.skyworth.web.common.Constants;
import com.skyworth.web.common.controller.BaseController;
import com.skyworth.web.common.form.MenuCss;
import com.skyworth.web.common.form.Paginator;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cody on 2016/8/11.
 */

@Controller
@RequestMapping("/admin/table")
public class TableController extends BaseController {

    Logger LOG = LoggerFactory.getLogger(TableController.class);

    @Autowired
    private ITableService iTableService;

    @Autowired
    private UserService userService;

    @Autowired
    private MenuCss menuCss;

    @RequiresRoles(value={Constants.TABLE_ROLE})
    @RequestMapping("")
    public String index(Paginator paginator, Model model) {
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }
        JsonObject params = null;
        params = new JsonObject();
        params.addProperty("store_id", store_id);

        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouDiningTable = "hover";
        model.addAttribute("menuCss", menuCss);
        model.addAttribute("user", userModel);
        Page<TableModel> page = iTableService.tablePage(params, paginator.pageRequest());
        paginator.feedToModel(page,model);
        return "admin/diningtable/diningtables";
    }


    @RequestMapping(value = {"new"})
    public String newAction(Model model) {
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }

        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouDiningTable = "hover";
        model.addAttribute("menuCss", menuCss);
        model.addAttribute("user", userModel);
        List<UserModel> userModels = userService.waiterList(store_id);
        model.addAttribute("waiters", userModels);
        return "admin/diningtable/diningtable_new";
    }

    @RequestMapping(value = {"{id}"}, method = RequestMethod.GET)
    public String edit(@PathVariable("id") long id, Model model) {
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }

        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouDiningTable = "hover";
        TableModel tableModel = iTableService.findTable(id);
        model.addAttribute("menuCss", menuCss);
        List<UserModel> userModels = userService.waiterList(store_id);
        model.addAttribute("waiters", userModels);
        model.addAttribute("table", tableModel);
        model.addAttribute("user", userModel);
        return "admin/diningtable/diningtable_edit";
    }

    @RequestMapping(value = {"{id}"}, method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> update(@PathVariable("id") long id,
                         @ModelAttribute TableForm tableForm,
                         Model model) {
        Map<String, Object> map = new HashMap<>();

        UserModel user = currentUser();
        model.addAttribute("user", currentUser());
        long store_id = 0;
        if(user!=null){
            store_id = user.storeId;
        }else {
            map.put("valid", false);
            map.put("errorMsg", "请先登陆");
            return map;
        }

        if(iTableService.existTableByStore(tableForm.getName(),store_id)){
            map.put("valid", false);
            map.put("errorMsg", tableForm.getName()+"已存在");
            return map;
        }
        TableModel tableModel = iTableService.updateTable(tableForm);

        model.addAttribute("table", tableModel);
        map.put("valid", true);
        map.put("url", "/admin/table");
        return map;
    }


    @RequestMapping(value = {"create"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(@ModelAttribute TableForm tableForm,
                         Model model) {
        Map<String, Object> map = new HashMap<>();

        UserModel user = currentUser();
        model.addAttribute("user", currentUser());
        long store_id = 0;
        if(user!=null){
            store_id = user.storeId;
        }else {
            map.put("valid", false);
            map.put("errorMsg", "请先登陆");
            return map;
        }
        if(iTableService.existTableByStore(tableForm.getName(), store_id)){
            map.put("valid", false);
            map.put("errorMsg", tableForm.getName() + "已存在");
            return map;
        }

        if(user!=null){
            tableForm.setStoreId(user.storeId);
        }else {
            tableForm.setStoreId(0);
        }
        TableModel tableModel = iTableService.addTable(tableForm);
        if(tableModel.id > 0){
            map.put("valid", true);
            map.put("url", "/admin/table");
        }else {
            map.put("valid", false);
            map.put("errorMsg", "添加台桌失败");
        }
        return map;
    }

    @RequestMapping(value = {"{id}"}, method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String,Object> delete(@PathVariable("id") long id) {
        Map<String, Object> rsp = responseMap();
        TableModel tableModel = iTableService.findTable(id);

        if (tableModel != null) {
            iTableService.removeTable(id);
            rsp.put("success", true);
        }else{
            rsp.put("success", false);
            rsp.put("message", "table doesn't exist");
        }
        return rsp;
    }

    @RequestMapping("qrcode")
    public String qrcode(Model model) {
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }

        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouDiningTable = "hover";
        model.addAttribute("menuCss", menuCss);
        model.addAttribute("user", userModel);

        List<TableModel> tableModels = (List<TableModel>) iTableService.queryByStoreId(store_id);
        model.addAttribute("tables", tableModels);

        return "admin/diningtable/qrcodes";
    }

   /* private static final String FilePath = "D:\\";
    @RequestMapping("qr_download")
    public String download(Model model, HttpServletResponse httpServletResponse) {
        //生成的ZIP文件名为qr.zip
        String tmpFileName = "qr.zip";
        byte[] buffer = new byte[1024];
        String strZipPath = FilePath + tmpFileName;
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    strZipPath));
            // 需要同时下载的两个文件result.txt ，source.txt
            File[] file1 = { new File(FilePath+"test1.txt"),
                    new File(FilePath+"测试2.docx") };
            for (int i = 0; i < file1.length; i++) {
                FileInputStream fis = new FileInputStream(file1[i]);
                out.putNextEntry(new ZipEntry(file1[i].getName()));
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            }
            out.close();
            this.downFile(httpServletResponse, tmpFileName);
        } catch (Exception e) {
            LOG.error("文件下载出错", e);
        }
        return null;
    }

    private void downFile(HttpServletResponse response, String str) {
        try {
            String path = FilePath + str;
            File file = new File(path);
            if (file.exists()) {
                InputStream ins = new FileInputStream(path);
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流
                BufferedOutputStream bouts = new BufferedOutputStream(outs);
                response.setContentType("application/x-download");// 设置response内容的类型
                response.setHeader(
                        "Content-disposition",
                        "attachment;filename="
                                + URLEncoder.encode(str, "UTF-8"));// 设置头部信息
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                // 开始向网络传输文件流
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();// 这里一定要调用flush()方法
                ins.close();
                bins.close();
                outs.close();
                bouts.close();
            } else {
                response.sendRedirect("../error.jsp");
            }
        } catch (IOException e) {
            LOG.error("文件下载出错", e);
        }
    }

    public void downloadNet() throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        URL url = new URL("windine.blogdriver.com/logo.gif");

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("c:/abc.gif");

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
            fs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }


        System.out.println("info:"+url+" download success");

    }



    *//**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     *//*
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) {
        try{
            downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",
                    "百度.jpg","d:/resource/images/diaodiao/country/");
        }catch (Exception e) {
            // TODO: handle exception
        }
    }*/
}
